package com.qfedu.openplateform.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qfedu.openplateform.cache.service.CacheService;
import com.qfedu.openplateform.common.constans.ExceptionDict;
import com.qfedu.openplateform.common.entity.ResponseData;
import com.qfedu.openplateform.gateway.config.ApplicationContextHolder;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取 token
        String token = request.getParameter("token");
        if (token!=null && !token.isEmpty()){

            // 解析 token
            Claims body = Jwts.parser().setSigningKey("meiyoumima".getBytes()).parseClaimsJws(token).getBody();
            String username = (String) body.get("username");

            // 获取 Spring 容器里的 CacheServiceBean
            ApplicationContext applicationContext = ApplicationContextHolder.getApplicationContext();
            CacheService cacheService = applicationContext.getBean(CacheService.class);

            String tokenFromRedis = cacheService.getFromRedis("token-" + username);

            System.out.println("token1"  + token);
            System.out.println("token2"  + tokenFromRedis);

            // 通过 username  获取redis对应的 token   和当前 token 进行对比
            if (token.equals(tokenFromRedis)){ // 放行
                // 放行
                return true;
            }else {   // 如果在一个地方登录之后，在另外一个地方再次登录，先前等的电脑必须重新登录 -----》唯一登录，只能在一个地方登录

                response.setContentType("application/json;charset=utf-8");
                ResponseData bean = new ResponseData();
                bean.setCode(ExceptionDict.SYSTEMPARAM_IDEMPOTENTS_ERROR);
                bean.setMessage("改token 不正确请求重新登录");
                try {
                    response.getWriter().println(JSON.toJSONString(bean));
                } catch (JsonProcessingException ex) {
                    ex.printStackTrace();
                }

                // 拦截
                return false;
            }


        }


        // 没有 token , 签名不对  拦截
        response.setContentType("application/json;charset=utf-8");
        ResponseData bean = new ResponseData();
        bean.setCode(ExceptionDict.SYSTEMPARAM_IDEMPOTENTS_ERROR);
        bean.setMessage("请传入token");
        try {
            response.getWriter().println(JSON.toJSONString(bean));
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }
        // 拦截
        return false;
    }
}
